/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { CompressionParameters } from './CompressionParameters'
import Long from '../util/long/index'
import Arrays from '../util/Arrays'

export default class BlockCompressionState {
    public hashTable: Int32Array;
    public chainTable: Int32Array;
    private baseAddress: Long;
    private windowBaseOffset: number = 0;

    constructor(parameters: CompressionParameters, baseAddress: Long) {
        this.baseAddress = baseAddress;
        this.hashTable = new Int32Array(1 << parameters.getHashLog());
        this.chainTable = new Int32Array(1 << parameters.getChainLog()); // TODO: chain table not used by Strategy.FAST
    }

    public reset(): void
    {
        Arrays.fill(this.hashTable, 0);
        Arrays.fill(this.chainTable, 0);
    }

    public enforceMaxDistance(inputLimit: Long, maxDistance: number): void {
        let distance: number = inputLimit.subtract(this.baseAddress).toNumber();

        let newOffset: number = distance - maxDistance;
        if (this.windowBaseOffset < newOffset) {
            this.windowBaseOffset = newOffset;
        }
    }

    public getBaseAddress(): Long
    {
        return this.baseAddress;
    }

    public getWindowBaseOffset(): number
    {
        return this.windowBaseOffset;
    }
}
